package cn.moukou.dictator.controller;

import cn.moukou.dictator.service.entity.CustomFileService;
import cn.moukou.dictator.util.OssUtil;
import cn.moukou.dictator.util.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/dictator/api/file")
public class FileController {
    @Autowired
    CustomFileService fileService;


    @PostMapping("/upload")
    public Resp<String> addFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Resp.fail("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        String filepath = "tmp/" + fileName;
        OssUtil.upload(filepath , file.getInputStream());
        fileService.addOneFile(fileName, filepath);
        return Resp.ok(OssUtil.getDownloadUrl(fileName,filepath));
    }

    @GetMapping("/download/url")
    public Resp<String> getDownloadUrl(@RequestParam("filename") String filename, @RequestParam("filepath") String filepath) throws UnsupportedEncodingException {
        return Resp.ok(OssUtil.getDownloadUrl(filename, filepath));
    }
}
